package com.剑指offer.第四章;

/**
 * 回文链表
 * <p>
 * 先使用快慢指针 找出中间的节点，然后让链表断开。将第二个链表反转 之后每个节点进行判断
 */
public class 回文链表 {

    public static boolean resolve(ListNode head) {

        ListNode slow = head;
        ListNode fast = head.next;

        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        // 偶数时 下一个节点就是第二个链表的第一个节点
        ListNode towNode = slow.next;
        // 奇数时，下下个节点时第二个链表的
        if (fast.next != null) {
            towNode = slow.next.next;
        }

        slow.next = null;
        return computer(head, convert(towNode));
    }

    public static ListNode convert(ListNode head) {
        ListNode cur = head;
        ListNode pre = null;
        while (cur != null) {
            // 先将下一个节点保存下来，防止链表断开找不到
            ListNode next = cur.next;
            // 指向前一个节点
            cur.next = pre;
            // 记录当前节点 用于下个节点指向它
            pre = cur;
            cur = next;

        }
        return pre;
    }

    public static boolean computer(ListNode head1, ListNode head2) {
        while (head1 != null && head2 != null) {
            if (head1.val != head2.val) {
                return false;
            }
            head1 = head1.next;
            head2 = head2.next;
        }
        return true;
    }


    public static void main(String[] args) {

    }

}
